//
//  KeyboardTextView.swift
//  customKeyboard
//
//  Created by changhongliang on 2017/8/15.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit

class KeyboardTextView: UITextView {

    // 插入表情
    func insertEmoticon(emoticon: KeyboardEmoticon)
    {
        // 1.插入Emoji表情
        // 1.1获取当前选中的位置
        if let str = emoticon.codeStr
        {
            // 1.2将emoji表情替换到当前选中的位置replaceSubrange
            if str != "\0"{
                let textRange = selectedTextRange
                replace(textRange!, withText: str)
                return
            }
            
        }
        // 2.插入图片表情
        if emoticon.png != nil {
            //1.创建表情字符串
            let attachment = KeyboardTextAttachment(emoticon: emoticon, font: font!)
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath ?? "")
            let s = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: (s + 1), height:(s + 1))
            attachment.chs = emoticon.chs
            let emoticonStr = NSAttributedString(attachment: attachment)
            //2.根据现在的TextView上的内容生成一个可变属性字符串
            //注意:属性字符候选有自己默认大小
            let strM = NSMutableAttributedString(attributedString:attributedText)
            //3.将表情字符串插入光标所在的位置
            //当我们将一个新的字符串替换到可变字符串时,这个字符串的大小会参照属性字符串中位置中插入位置上一个字符串的大小
            strM.replaceCharacters(in:selectedRange, with: emoticonStr)
            //插入的表情会参照前面一个的大小, 所以每次设置完毕之后都需要重新设置一次前面一个的大小
            strM.addAttribute(NSFontAttributeName, value:font!, range: NSMakeRange(selectedRange.location, selectedRange.length + 1))
            //4.将新的字符串设置给TextView
            attributedText = strM
            //5.重新设置光标所在的位置
            selectedRange = NSMakeRange(selectedRange.location + 1, 0)
            return
        }
        
        if emoticon.isRemoveButton {
            deleteBackward()
        }

    }
    
    /// 获取TextView中的微博内容
    func emoticonString() -> String
    {
        var strM = String()
        attributedText.enumerateAttributes(in: NSMakeRange(0, attributedText.length), options: [NSAttributedString.EnumerationOptions(rawValue: 0)], using: {(dict: [String : Any], range, _) -> Void in
            
            if let attachment = dict["NSAttachment"]as? KeyboardTextAttachment
            {
                strM += attachment.chs ?? ""
                
            }else{
                let res = (attributedText.string as NSString).substring(with: range)
                strM += res
            }
        })
      return strM
    }
    
 
}
